package controller

import (
	"fmt"
	"io"
	"os"
	"time"

	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/sessions"

	uuid "github.com/satori/go.uuid"
	"github.com/wuriyanto48/replacer"

	"gitee.com/fx8s/goIrisTest/src/modules/profile/model"
	"gitee.com/fx8s/goIrisTest/src/modules/profile/usecase"

	storyModel "gitee.com/fx8s/goIrisTest/src/modules/story/model"
)

//ProfileIdKey
const ProfileIdKey = "profileId"

//ProfileController
type ProfileController struct {
	Ctx            iris.Context
	Session        *sessions.Session
	ProfileUsecase usecase.ProfileUsercase
}

//getCurrentProfileId
func (c *ProfileController) getCurrentProfileId() string {
	return c.Session.GetString(ProfileIdKey)
}

// isProfileLoggedIn
func (c *ProfileController) isProfileLoggedIn() bool {
	return c.getCurrentProfileId() != ""
}

// logout
func (c *ProfileController) logout() {
	c.Session.Destroy()
}

//GetRegister get
func (c *ProfileController) GetRegister() mvc.Result {
	if c.isProfileLoggedIn() {
		c.logout()
	}

	return mvc.View{
		Name: "profile/register.html",
		Data: iris.Map{"Title": "Profile 注册"},
	}
}

//人员注册 post
func (c *ProfileController) PostRegister() mvc.Result {
	firsName := c.Ctx.FormValue("FirsName")
	lastName := c.Ctx.FormValue("LastName")
	email := c.Ctx.FormValue("Email")
	password := c.Ctx.FormValue("Password")

	if firsName == "" || lastName == "" || email == "" || password == "" {
		return mvc.Response{
			Path: "/profile/register",
		}
	}

	id := uuid.NewV4()

	profileImage, err := c.uploadImage(c.Ctx, id.String())

	if err != nil {
		return mvc.Response{
			Path: "/profile/register",
		}
	}

	var profile model.Profile
	profile.ID = id.String()
	profile.FirsName = firsName
	profile.LastName = lastName
	profile.Email = email
	profile.Password = password
	profile.ImageProfile = profileImage
	profile.CreateAt = time.Now()
	profile.UpdateAt = time.Now()

	_, err = c.ProfileUsecase.SaveProfile(&profile)
	if err != nil {
		return mvc.Response{
			Path: "/profile/register",
		}
	}

	c.Session.Set(ProfileIdKey, profile.ID)

	return mvc.Response{
		Path: "/profile/me",
	}
}

//进入story操作
func (c *ProfileController) GetStory() mvc.Result {
	if !c.isProfileLoggedIn() {
		return mvc.Response{
			Path: "/profile/login",
		}
	}

	return mvc.View{
		Name: "/profile/story.html",
		Data: iris.Map{"Title": "新故事"},
	}

}

//人员注册 post
func (c *ProfileController) PostStory() mvc.Result {
	title := c.Ctx.FormValue("Title")
	content := c.Ctx.FormValue("Content")

	if title == "" || content == "" {
		return mvc.Response{
			Path: "/profile/story",
		}
	}

	id := uuid.NewV4()

	var entity storyModel.Story
	entity.ID = id.String()
	entity.Title = title
	entity.Content = content

	entity.CreateAt = time.Now()
	entity.UpdateAt = time.Now()

	profile, err := c.ProfileUsecase.GetById(c.getCurrentProfileId())
	if err != nil {
		c.logout()
		return c.GetMe()
		// return mvc.Response{
		// 	Path: "/profile/login",
		// }
	}

	entity.Profile = profile

	_, err = c.ProfileUsecase.SaveStory(&entity)
	if err != nil {
		c.logout()
		return c.GetMe()
		// return mvc.Response{
		// 	Path: "/profile/login",
		// }
	}

	return mvc.Response{
		Path: "/profile/story",
	}
}

//登录操作
func (c *ProfileController) GetLogin() mvc.Result {
	if c.isProfileLoggedIn() {
		c.logout()
	}

	return mvc.View{
		Name: "/profile/login.html",
		Data: iris.Map{"Title": "登录"},
	}

}

func (c *ProfileController) PostLogin() mvc.Result {
	email := c.Ctx.FormValue("Email")
	password := c.Ctx.FormValue("Password")

	if email == "" || password == "" {
		return mvc.Response{
			Path: "/profile/login",
		}
	}

	profile, err := c.ProfileUsecase.GetByEmail(email)

	if err != nil {
		return mvc.Response{
			Path: "/profile/login",
		}
	}

	if !profile.IsValidPassword(password) {
		return mvc.Response{
			Path: "/profile/login",
		}
	}

	c.Session.Set(ProfileIdKey, profile.ID)

	return mvc.Response{
		Path: "/profile/me",
	}
}

func (c *ProfileController) GetMe() mvc.Result {
	if !c.isProfileLoggedIn() {
		return mvc.Response{
			Path: "/profile/login",
		}
	}

	profile, err := c.ProfileUsecase.GetById(c.getCurrentProfileId())

	if err != nil {
		c.logout()
		c.GetMe()
	}

	return mvc.View{
		Name: "profile/me.html",
		Data: iris.Map{
			"Title":       "我的信息",
			"profileInfo": fmt.Sprintf("%s %s", profile.FirsName, profile.LastName),
			"profile":     profile,
		},
	}
}

func (c *ProfileController) AnyLogout() {

	if c.isProfileLoggedIn() {
		c.logout()
	}

	c.Ctx.Redirect("/profile/login")

	// return mvc.Response{
	// 	Path: "/profile/login",
	// }
}

//upload 图片
func (c *ProfileController) uploadImage(ctx iris.Context, id string) (string, error) {
	file, info, err := ctx.FormFile("ImageProfile")
	if err != nil {
		return "", err
	}

	defer file.Close()

	fileName := fmt.Sprintf("%s%s%s", id, "_", replacer.Replace(info.Filename, "_"))

	out, err := os.OpenFile("./web/public/images/profile/"+fileName, os.O_WRONLY|os.O_CREATE, 0666)

	if err != nil {
		return "", err
	}

	defer out.Close()

	io.Copy(out, file)

	return fileName, nil
}
